package com.bizark.rpc.common.tool;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;


public class GsonUtil {

    public enum GsonInstance {
        INSTANCE;
        private Gson instance;

        GsonInstance() {
            instance = new Gson();
//        	instance = new GsonBuilder()
//                    .setLenient()// json宽松
//                    .create();

        }

        public Gson getInstance() {
            return instance;
        }
    }


    /**
     * 任意类型对象转换成 json 字符串
     *
     * @param object
     * @return
     */
    public static String getJsonForObject(Object object) {
        Gson gson = GsonInstance.INSTANCE.getInstance();
        String jsonString = null;
        if (gson != null) {
            jsonString = gson.toJson(object);
        }
        return jsonString;
    }


    /**
     * json字符串转换成bean
     *
     * @param jsonString
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T jsonToBean(String jsonString, Class<T> cls) {
        Gson gson = GsonInstance.INSTANCE.getInstance();
        T t = null;
        if (gson != null) {
            t = gson.fromJson(jsonString, cls);
        }
        return t;
    }


    /**
     * json字符串转换成bean
     *
     * @param jsonString
     * @param type
     * @return
     */
    public static <T> T jsonToBean(String jsonString, Type type) {
        Gson gson = GsonInstance.INSTANCE.getInstance();
        T t = null;
        if (gson != null) {
            t = gson.fromJson(jsonString, type);
        }
        return t;
    }




    /**
     * json字符串转换成List
     *
     * @param jsonString
     * @param <T>
     * @return
     */
    public static <T> List<T> jsonToList(String jsonString) {
        Gson gson = GsonInstance.INSTANCE.getInstance();
        List<T> list = null;
        if (gson != null) {
            list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
            }.getType());
        }
        return list;
    }

    /**
     * 转换json字符串为Map
     *
     * @param jsonString
     * @param <T>
     * @return
     */
    public static <T> Map<String, T> GsonToMaps(String jsonString) {
        Gson gson = GsonInstance.INSTANCE.getInstance();
        Map<String, T> map = null;
        if (gson != null) {
            map = gson.fromJson(jsonString, new TypeToken<Map<String, T>>() {
            }.getType());
        }
        return map;
    }


}
